<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = [
            { id: 1, name: 'aa', parentId: null },
            { id: 2, name: 'bb', parentId: 1 },
            { id: 3, name: 'cc', parentId: 2 },
            { id: 4, name: 'dd', parentId: 3 },
            { id: 5, name: 'ee', parentId: 4 },
        ]
        function toTree(arrs) {
            var obj = {}
            var result =[]
            arrs.forEach(element => {
                if(element.parentId===null){
                    result.push(element)
                }
                obj[element.id] = element
            });
            arrs.forEach(item=>{
                if(item.parentId){
                  var parent = obj[item.parentId]
                  if(parent.child==null){
                      parent.child = []
                  }
                  parent.child.push(item)
                }
            })
            return result
        }
        console.log(toTree(arr));
    </script>
</body>

</html>